//
//  HomePageVC.swift
//  ListenFM
//
//  Created by 胡定锋Mac on 2017/8/4.
//  Copyright © 2017年 胡定锋. All rights reserved.
//

import UIKit
import Alamofire
import LLCycleScrollView

//import CategoryCell

class HomePageVC: BaseScene ,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
    
    var mainDict:(NSDictionary) = NSDictionary.init();
    var collectionview : UICollectionView?
    var model:HomePageModel?
    
 

    lazy var bannerView : LLCycleScrollView = {
        
        let bannerDemo = LLCycleScrollView.llCycleScrollViewWithFrame(CGRect.init(x: 0, y: 0, width: self.view.bounds.size.width, height: self.view.bounds.size.width/2))
        // 是否自动滚动
        bannerDemo.autoScroll = true
        
        // 是否无限循环，此属性修改了就不存在轮播的意义了 😄
        bannerDemo.infiniteLoop = true
        
        // 滚动间隔时间(默认为2秒)
        bannerDemo.autoScrollTimeInterval = 3.0
        
        // 等待数据状态显示的占位图
        bannerDemo.placeHolderImage = nil;
        
        // 如果没有数据的时候，使用的封面图
        bannerDemo.coverImage = nil;
        
        // 设置图片显示方式=UIImageView的ContentMode
        bannerDemo.imageViewContentMode = .scaleToFill
        
        // 设置滚动方向（ vertical || horizontal ）
        bannerDemo.scrollDirection = .horizontal
        
        // 设置当前PageControl的样式 (.none, .system, .fill, .pill, .snake)
        bannerDemo.customPageControlStyle = .snake
        
        // 非.system的状态下，设置PageControl的tintColor
        bannerDemo.customPageControlInActiveTintColor = UIColor.red
        
        // 设置.system系统的UIPageControl当前显示的颜色
        bannerDemo.pageControlCurrentPageColor = UIColor.white
        
        // 非.system的状态下，设置PageControl的间距(默认为8.0)
        bannerDemo.customPageControlIndicatorPadding = 8.0
        
        // 设置PageControl的位置 (.left, .right 默认为.center)
        bannerDemo.pageControlPosition = .center
        
        // 背景色
        bannerDemo.collectionViewBackgroundColor = UIColor.white;
        
        
        // 模拟网络图片获取
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(2)) {
            bannerDemo.imagePaths = ["http://ossimg.xinli001.com/20170803/8ffdc4cdf16d5e1034efe9d4b3e3caf2.jpg","http://ossimg.xinli001.com/20170802/7637abf6a40fa372982b03102baa5a6c.png","http://ossimg.xinli001.com/20170522/ed9e21e6d78d858510d7e7fd205f4110.png"]
        }
        return bannerDemo
        
    }()
    
    // 集合视图的懒加载
    lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout.init()
        layout.itemSize = .init(width: UIScreen.main.bounds.size.width/4, height: UIScreen.main.bounds.size.width/4)
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.sectionInset = .init(top: 0, left: 0, bottom: 0, right: 0)
        
        let collection = UICollectionView.init(frame: .init(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height), collectionViewLayout: layout)
        collection.delegate = self
        collection.dataSource = self
        collection.backgroundColor = UIColor.white
        collection.register(UINib(nibName:"CategoryCell", bundle:nil),forCellWithReuseIdentifier: "CategoryCell")
        collection.register(UINib(nibName:"RecommendCell", bundle:nil),forCellWithReuseIdentifier: "RecommendCell")
        
        collection.register(UINib(nibName:"HomeListCell", bundle:nil),forCellWithReuseIdentifier: "HomeListCell")
        
        collection.register(UINib(nibName:"HeaderView", bundle:nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "HeaderView")
        
        //        collection.addSubview(creatBannerView(imageArr: ["http://ossimg.xinli001.com/20170803/8ffdc4cdf16d5e1034efe9d4b3e3caf2.jpg","http://ossimg.xinli001.com/20170802/7637abf6a40fa372982b03102baa5a6c.png","http://ossimg.xinli001.com/20170522/ed9e21e6d78d858510d7e7fd205f4110.png"]))
        
        return collection
    }()

    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "首页"
//        self.automaticallyAdjustsScrollViewInsets = true
        getRequest();
        
    }

    public func creatBannerView(imageArr : Array<String>? = []) -> LLCycleScrollView {
        
        let bannerDemo = LLCycleScrollView.llCycleScrollViewWithFrame(CGRect.init(x: 0, y: 0, width: self.view.bounds.size.width, height: self.view.bounds.size.width/2))
        // 是否自动滚动
        bannerDemo.autoScroll = true
        
        // 是否无限循环，此属性修改了就不存在轮播的意义了 😄
        bannerDemo.infiniteLoop = true
        
        // 滚动间隔时间(默认为2秒)
        bannerDemo.autoScrollTimeInterval = 3.0
        
        // 等待数据状态显示的占位图
        bannerDemo.placeHolderImage = nil;
        
        // 如果没有数据的时候，使用的封面图
        bannerDemo.coverImage = nil;
        
        // 设置图片显示方式=UIImageView的ContentMode
        bannerDemo.imageViewContentMode = .scaleToFill
        
        // 设置滚动方向（ vertical || horizontal ）
        bannerDemo.scrollDirection = .horizontal
        
        // 设置当前PageControl的样式 (.none, .system, .fill, .pill, .snake)
        bannerDemo.customPageControlStyle = .snake
        
        // 非.system的状态下，设置PageControl的tintColor
        bannerDemo.customPageControlInActiveTintColor = UIColor.red
        
        // 设置.system系统的UIPageControl当前显示的颜色
        bannerDemo.pageControlCurrentPageColor = UIColor.white
        
        // 非.system的状态下，设置PageControl的间距(默认为8.0)
        bannerDemo.customPageControlIndicatorPadding = 8.0
        
        // 设置PageControl的位置 (.left, .right 默认为.center)
        bannerDemo.pageControlPosition = .center
        
        // 背景色
        bannerDemo.collectionViewBackgroundColor = UIColor.white;

        
        // 模拟网络图片获取
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(2)) {
            bannerDemo.imagePaths = imageArr!
        }
        return bannerDemo
    }

    
    func getRequest() -> Void {
        
        Alamofire.request("http://yiapi.xinli001.com/fm/home-list.json?key=c0d28ec0954084b4426223366293d190", parameters: nil)
            .responseJSON { response in
                switch response.result.isSuccess {
                case true:
                    
                    if let items = response.result.value as? NSDictionary{
                        
                        self.mainDict = items;
                        
                        print(items);
                        self.model = HomePageModel.deserialize(from: self.mainDict)
                        
                        self.view.addSubview(self.collectionView)

                        self.collectionView.addSubview(self.bannerView)
                        
                        self.collectionView.reloadData()
                    }
                    
                    
                case false:
                    print(response.result.error as Any)
                }
        }
        
    }
    
    
//# collectionviewDelegate datasoure
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat
    {//item的水平间距
        if section == 1 {
            return 10
        }else {
            return 0
        }
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat
    {
        //item的垂直间距
        if section == 1 {
            return 10
        }else if section == 2 {
            return 10
        }else if section == 3 {
            return 10
        }else{
            return 0
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize{
        
        if section == 0 {
            
            return CGSize.init(width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.width/2)
        }else{
            
            return CGSize.init(width: UIScreen.main.bounds.size.width, height: 30)
        }
    }

    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView{
        
        if kind == UICollectionElementKindSectionHeader {
            let headerView : HeaderView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader,withReuseIdentifier:"HeaderView", for: indexPath) as! HeaderView
            headerView.titleLabel.text = ["","精彩推荐","最新fm","最新心理课","最新电台"][indexPath.section]
            return headerView
            
        } else {
            return UICollectionReusableView()
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize{
        
        if indexPath.section == 1 {
          
            return CGSize.init(width: (UIScreen.main.bounds.size.width-60)/3, height: (UIScreen.main.bounds.size.width-60)/6+30)
        }else  if indexPath.section == 2 {
            
            return CGSize.init(width: UIScreen.main.bounds.size.width, height: 65)
        }else  if indexPath.section == 3 {
            
            return CGSize.init(width: UIScreen.main.bounds.size.width, height: 65)
        }
        else{
            return CGSize.init(width: UIScreen.main.bounds.size.width/4, height: UIScreen.main.bounds.size.width/4)
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets{
        
        if section == 0 {
            
            return UIEdgeInsetsMake(0, 0, 0, 0)
        }
        else if section == 1
        {
            return UIEdgeInsetsMake(10, 10, 10, 10)
            
        }else if section == 2
        {
            return UIEdgeInsetsMake(10, 0, 10, 0)
            
        }else if section == 3
        {
            return UIEdgeInsetsMake(10, 0, 10, 0)
            
        }else{
            
            return UIEdgeInsetsMake(0, 0, 0, 0)
        }
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        
        return 5
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if section == 0 {
            return (self.model?.data.category.count)!
        }else if section == 1
        {
            return (self.model?.data.hotfm.count)!
        }else if section == 2
        {
            return (self.model?.data.newfm.count)!
        }
        else if section == 3{
            return (self.model?.data.newlesson.count)!
        }
        else if section == 4{
            return (self.model?.data.diantai.count)!
        }else{
            return 0
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell : UICollectionViewCell?
        
        if indexPath.section == 1 {
            
            cell  = collectionView.dequeueReusableCell(withReuseIdentifier: "RecommendCell",
                                                           for: indexPath) as! RecommendCell
            let recommendcell:RecommendCell = cell as! RecommendCell
            
            recommendcell.model = self.model?.data.hotfm[indexPath.item]
            
        }else if indexPath.section == 2 {
            
            cell  = collectionView.dequeueReusableCell(withReuseIdentifier: "HomeListCell",
                                                       for: indexPath) as! HomeListCell
            
            let homelistcell:HomeListCell = cell as! HomeListCell
            
            homelistcell.model = self.model?.data.newfm[indexPath.item]
            
        }else if indexPath.section == 3 {
            
            cell  = collectionView.dequeueReusableCell(withReuseIdentifier: "HomeListCell",
                                                       for: indexPath) as! HomeListCell
            let homelistcell:HomeListCell = cell as! HomeListCell
            
            homelistcell.lessonModel = self.model?.data.newlesson[indexPath.item]
        }
        else if indexPath.section == 0
        {
            cell  = collectionView.dequeueReusableCell(withReuseIdentifier: "CategoryCell",
                                                       for: indexPath) as! CategoryCell
            let categorycell:CategoryCell = cell as! CategoryCell
            
            categorycell.categoryModel = self.model?.data.category[indexPath.item]
            
        }else{
            
            cell  = collectionView.dequeueReusableCell(withReuseIdentifier: "CategoryCell",
                                                       for: indexPath) as! CategoryCell
            
            let categorycell:CategoryCell = cell as! CategoryCell
            
            categorycell.diantaiModel = self.model?.data.diantai[indexPath.item]

        }
        return cell!
    }
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print(indexPath.row)
        
        if indexPath.section == 1 {
            
            let model : hotfmSubModel = (self.model?.data.hotfm[indexPath.item])!
            
            let playervc : PlayerVC = PlayerVC.init()
            playervc.hidesBottomBarWhenPushed = true
            playervc.broadcast_id = model.id as NSString
            self.navigationController?.pushViewController(playervc, animated: true)
        }
        
    }
    
}

